package com.contacts.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;

import com.contacts.pojo.User;
import com.contacts.service.UserService;


public class RegisterServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//设置编码
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		User user=new User();
		
		try {
			BeanUtils.populate(user, request.getParameterMap());
			
			UserService us=new UserService();
			us.addUser(user);
			//注册成功
			request.getSession().setAttribute("loginmsg", "注册成功，欢迎登陆");
			response.sendRedirect(request.getContextPath()+"/login.jsp");
			return;
		} catch (Exception e) {
			request.setAttribute("loginmsg", "账号已经存在");
			request.getRequestDispatcher("/register.jsp").forward(request, response);
			e.printStackTrace();
		} 
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doGet(request, response);
	}

}
